package com.demo.las.controller;

import com.demo.las.dto.ApiResponse;
import com.demo.las.entity.User;
import com.demo.las.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.Map;

@RestController
@RequestMapping("/api/auth")
@CrossOrigin(origins = "*")
public class AuthController {

    @Autowired
    private AuthService authService;

    @PostMapping("/login")
    public ApiResponse<Map<String, Object>> login(@RequestBody Map<String, String> loginRequest) {
        try {
            String usernameOrEmail = loginRequest.get("username");
            String password = loginRequest.get("password");
            
            if (usernameOrEmail == null || password == null) {
                return ApiResponse.error("用户名和密码不能为空");
            }
            
            Map<String, Object> result = authService.login(usernameOrEmail, password);
            return ApiResponse.success("登录成功", result);
        } catch (RuntimeException e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    @PostMapping("/register")
    public ApiResponse<User> register(@Valid @RequestBody User user) {
        try {
            User registeredUser = authService.register(user.getUsername(), user.getPassword(), user.getEmail());
            return ApiResponse.success("注册成功", registeredUser);
        } catch (RuntimeException e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    @PostMapping("/logout")
    public ApiResponse<Void> logout(@RequestBody Map<String, String> logoutRequest) {
        try {
            String sessionId = logoutRequest.get("sessionId");
            if (sessionId != null) {
                authService.logout(sessionId);
            }
            return ApiResponse.success("登出成功", null);
        } catch (Exception e) {
            return ApiResponse.error("登出失败");
        }
    }
}
